package controllers

import (
	"alarmservice/com"
	"alarmservice/model"
	"alarmservice/service"
	"encoding/json"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
	"github.com/beego/wetalk/modules/utils"
	simplejson "github.com/bitly/go-simplejson"
	cache "github.com/pmylund/go-cache"
)

var DefaultAdminUser *model.AdminUser

type baseControllerInterface interface {
	beego.ControllerInterface
	NextPrepare()
}

type MainController struct {
	baseController
}

func (c *MainController) Get() {
	c.Data["Website"] = "beego"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "index.tpl"
}

type baseController struct {
	beego.Controller
	NeedLogin bool
	AdminUser *model.AdminUser
	Uid       int64
}

func (c *baseController) Prepare() {
	c.Data["BreadCrumb"] = make([][2]string, 0)

	c.paddingGetPost()
	c.initAdminUser()

	//ProjectController执行
	if app, ok := c.AppController.(baseControllerInterface); ok {
		app.NextPrepare()
	}

	if c.NeedLogin && c.AdminUser.Id <= 0 {
		c.Redirect("/login", 302)
	}
}

func (c *baseController) AddBreadCrumb(title string, url string) {
	if len(title) <= 0 || len(url) <= 0 {
		return
	}

	c.Data["BreadCrumb"] = append(c.Data["BreadCrumb"].([][2]string), [2]string{title, url})
	return
}

func (c *baseController) SetFormErrsToJson(formErrs map[string]*validation.Error) {
	c.Data["FormErrs"] = formErrs
	j := simplejson.New()
	j.SetPath(make([]string, 0), formErrs)

	jsonBytes, err := j.MarshalJSON()
	if err != nil {
		beego.Error(err)
		c.Abort("500")
		return
	}
	c.Data["FormErrsJson"] = string(jsonBytes)
}

func (c *baseController) UseLayout() {
	//设置laylout
	c.Layout = "common/baselayout.tpl"
	c.LayoutSections = make(map[string]string)
	c.LayoutSections["Sidebar"] = "common/siderbar.tpl"
}

func (c *baseController) initAdminUser() {
	c.AdminUser = DefaultAdminUser
	c.Uid = 0

	uid, ok := c.Ctx.Input.CruSession.Get("uid").(int64)

	if ok {
		adminUser, err := model.GetAdminUserById(uid)
		if err == nil {
			c.AdminUser = adminUser
			c.Uid = uid
			c.Data["AdminUser"] = adminUser
			c.Data["Uid"] = uid
		}
	}
}

func (c *baseController) initFlashData() {
	flashData := beego.ReadFromRequest(&c.Controller)

	c.Data["FlashData"] = flashData

	jBytes, err := json.Marshal(flashData)
	if err != nil {
		c.Data["FlashDataJson"] = "{}"
	} else {
		c.Data["FlashDataJson"] = string(jBytes)
	}
}

func (c *baseController) SetPaginator(per int, nums int64) *utils.Paginator {
	p := utils.NewPaginator(c.Ctx.Request, per, nums)
	c.Data["paginator"] = p
	return p
}

func (c *baseController) paddingGetPost() {
	c.Ctx.Request.ParseForm()

	c.Data["FormVar"] = c.Ctx.Request.Form
	c.Data["PostFormVar"] = c.Ctx.Request.PostForm

	getVars := make(map[string]string)
	postVars := make(map[string]string)
	for k, v := range c.Ctx.Request.Form {
		vLen := len(v)
		if vLen > 0 {
			getVars[k] = v[len(v)-1]
		} else {
			getVars[k] = ""
		}
	}

	for k, v := range c.Ctx.Request.PostForm {
		vLen := len(v)
		if vLen > 0 {
			postVars[k] = v[len(v)-1]
		} else {
			postVars[k] = ""
		}
	}

	c.Data["GET"] = getVars
	c.Data["POST"] = postVars
}

func (c *baseController) returnJson(j *com.JsonApiRep, encode ...bool) {
	c.Data["json"] = j
	c.ServeJSON(encode...)
	return
}

var controllerCache *cache.Cache

func init() {
	controllerCache = service.Cache
	DefaultAdminUser = &model.AdminUser{}
}
